package com.twu.biblioteca.factory;

import com.twu.biblioteca.*;
import com.twu.biblioteca.User.User;
import com.twu.biblioteca.exception.InvalidOptionException;

import java.util.InputMismatchException;

public class BorrowAction extends BasicAction {

    private final int BOOK = 1;
    private final int MOVIE = 2;

    private BorrowAction() {
    }

    private static BorrowAction borrowAction = null;

    public synchronized static BorrowAction getInstance() {
        if (borrowAction == null) {
            borrowAction = new BorrowAction();
        }
        return borrowAction;
    }

    public void setBookBorrower(String bookName, User borrower, Shelf shelf) {
        shelf.setBorrower(bookName, borrower);
    }

    @Override
    public void run(BibliotecaApp bibliotecaApp, Receiver receiver) {
        int chooseFunction = chooseFunction(receiver);
        Shelf shelf = null;
        if (chooseFunction == BOOK) {
            shelf = bibliotecaApp.getBookShelf();
        } else if (chooseFunction == MOVIE) {
            shelf = bibliotecaApp.getMovieShelf();
        } else {
            return;
        }
        shelf.showAllGoods();
        String chooseBookName = inputValidBorrowGoodsName(receiver, shelf);
        setBookBorrower(chooseBookName, bibliotecaApp.getCurrentUser(), bibliotecaApp.getBookShelf());
    }

    private int chooseFunction(Receiver receiver) {
        Println.println(Println.BORROW_CATEGORIES);
        int chosenFunction = 0;
        while (true) {
            try {
                chosenFunction = receiver.getDataInt();
                if (chosenFunction == BOOK || chosenFunction == MOVIE) {
                    return chosenFunction;
                } else {
                    throw new InvalidOptionException();
                }
            } catch (InputMismatchException exception) {
                receiver.getData();
                Println.println(Println.INVALID_OPTION);
                continue;
            } catch (InvalidOptionException e) {
                Println.println(Println.INVALID_OPTION);
                continue;
            }

        }
    }

}
